using System;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
using System.Collections;
using Audio;
using DG.Tweening;
using TMPro;

namespace UI.ExamplePanel
{
    public enum EmotionType
    {
        Low,
        High,
        Middle
    }

    /// <summary>
    /// 示例面板，游戏中的面板，可以在这添加类似血条等GamingUI
    /// </summary>
    public class GamePanel : BasePanel<GamePanel>
    {
        public Image dark;                      //切换角色黑幕
        private Image bg;                       //背景
        private Image guestInfo;                //角色介绍面板（病例）
        private Image guest;                    //角色图片
        private Image emoji;                    //角色表情
        private TextMeshProUGUI turnCount;      //显示回合数
        private TextMeshProUGUI canAttackCount; //显示当前回合可打出的卡牌数
        [HideInInspector] public Button endTurn;//结束回合按钮

        //角色每回合的debuff（例如每回合10%抵抗）

        private Transform emotionGo;            //情绪轴的引用
        private List<Image> emotions;           //情绪轴条的控制位置的引用
        public List<RectTransform> targetEmoPos;//情绪轴目标的位置（那个三角形）
        public List<TextMeshProUGUI> targetEmoCount;    //目标情绪轴当前数字
        private Dictionary<Image, Coroutine> activeBarCoroutine = new Dictionary<Image, Coroutine>();      //维护每个bar的协程，防止多个协程冲突

        private void Start()
        {
            CoroutineManager.Instance.AddTask(CoreMechanismManager.Instance.EnterGuest());
            AudioManager.Instance.ManagerMusic("State1", true);
        }

        public override void Init()
        {
            base.Init();

            // 获得 UI并初始化
            bg = transform.Find("BackGround").GetComponent<Image>();
            guestInfo = transform.Find("GuestInfo").GetComponent<Image>();
            guest = transform.Find("GuestPanel/Guest").GetComponent<Image>();
            emoji = transform.Find("GuestPanel/Emoji").GetComponent<Image>();
            turnCount = transform.Find("CardGamePanel/TurnData/Turn/TurnText").GetComponent<TextMeshProUGUI>();
            canAttackCount = transform.Find("CardGamePanel/TurnData/CanAttack/CanAttackText").GetComponent<TextMeshProUGUI>();
            endTurn = transform.Find("CardGamePanel/EndRound").GetComponent<Button>();

            emotionGo = transform.Find("GuestInfo/emotion");
            emotions = new List<Image>();

            foreach (Transform child in emotionGo)
            {
                Image img = child.transform.GetChild(1).GetComponent<Image>();
                if (img != null)
                {
                    emotions.Add(img);
                }
            }
            //CoroutineManager.Instance.AddTask(CoreMechanismManager.Instance.EnterGuest());
        }

        public void ShowMeNew(int id)
        {
            ShowMe();
            CoroutineManager.Instance.ForceStart(CoreMechanismManager.Instance.EnterGuest());
        }

        public override void OnPressedEsc()
        {
            GamePausePanel.Instance.ShowMe();
        }

        /// <summary>
        /// 更新GamePanel的UI和数据变化
        /// </summary>
        /// <param name="guest"></param>
        /// <param name="isPunish"></param>
        public void UpdateGuestUI(Guest guest, bool isPunish = false)
        {
            this.guest.sprite = Resources.Load<Sprite>(guest.path);
            guestInfo.sprite = Resources.Load<Sprite>(guest.infoPath);
            var targetEmotion = GuestManager.Instance.GetStage(guest, GameManager.Instance.curState).targetEmotion;

            for (int i = 0; i < emotions.Count && i < 2; i++)
            {
                //通过变化使其范围在-100到100
                float targetNum = targetEmotion[i];
                targetNum += 100;
                targetNum /= 200;

                //目标值三角标的位置
                float posX = 1200 * targetNum;
                targetEmoPos[i].anchoredPosition = new Vector2(posX - 600, targetEmoPos[i].anchoredPosition.y);

                float num = guest.currentEmotion[i];
                num += 100;
                num /= 200;
                if (activeBarCoroutine.TryGetValue(emotions[i], out var curCoroutine))
                {
                    StopCoroutine(curCoroutine);
                    activeBarCoroutine.Remove(emotions[i]);
                }

                //绘制条的位置
                activeBarCoroutine.Add(emotions[i], StartCoroutine(BarChangeAnim(emotions[i], num, 0.3f)));
                //TODO: 绘制目标情绪的位置
            }
            targetEmoCount[0].text = guest.GetBarData(false).ToString();
            targetEmoCount[1].text = guest.GetBarData(true).ToString();
        }

        /// <summary>
        /// 更新当前可攻击次数
        /// </summary>
        /// <param name="curTurn"></param>
        /// <param name="curAttackNum"></param>
        public void UpdateAttackTurnUI(int curTurn, int curAttackNum)
        {
            turnCount.text = curTurn.ToString();
            canAttackCount.text = curAttackNum.ToString();
        }

        /// <summary>
        /// 获取当前角色的emoji并且加载出来
        /// </summary>
        /// <param name="guest"></param>
        /// <param name="emotion">传入的emoji名字</param>
        public void GetGuestEmoji(string guest, string emotion)
        {
            string spriteName = null;

            spriteName = guest + "/" + emotion;
            string path = "Arts/Emoji/" + spriteName;
            Sprite emo = Resources.Load<Sprite>(path);
            if (emo == null)
            {
                emoji.enabled = false;
                return;
            }
            emoji.enabled = true;
            this.emoji.sprite = emo;

        }

        /// <summary>
        /// 控制游玩的背景图片和角色是否显示
        /// </summary>
        /// <param name="isTrue"></param>
        public void ShowGuest(bool isTrue)
        {
            if (isTrue)
            {
                bg.sprite = Resources.Load<Sprite>("Arts/GamePanel/bg");
                guest.enabled = true;
                guestInfo.gameObject.SetActive(true);
                endTurn.gameObject.SetActive(true);
            }
            else
            {
                AudioManager.Instance.PauseBGM();
                bg.sprite = Resources.Load<Sprite>("Arts/Gray");
                guest.enabled = false;
                guestInfo.gameObject.SetActive(false);
                endTurn.gameObject.SetActive(false);
            }
        }

        /// <summary>
        /// 做入场动画
        /// </summary>
        public void DoGuestAnimation()
        {
            // 2. 初始化透明度与位置，用于动画起点
            Color guestColor = this.guest.color;
            guestColor.a = 0f; // 从完全透明开始
            this.guest.color = guestColor;

            RectTransform rt = guestInfo.GetComponent<RectTransform>();
            Vector2 guestInfoStartPos = new Vector2(-315f, rt.anchoredPosition.y);
            rt.anchoredPosition = guestInfoStartPos;
            Vector2 guestInfoTargetPos = new Vector2(315f, rt.anchoredPosition.y);

            // 3. 播放动画
            Sequence seq = DOTween.Sequence();
            seq.Append(this.guest.DOFade(1f, 0.6f).SetEase(Ease.OutQuad)); // 渐显
            seq.Join(rt.DOAnchorPosX(guestInfoTargetPos.x, 0.6f).SetEase(Ease.OutBack));
            seq.Play();
        }

        /// <summary>
        /// 轴的动画变化
        /// </summary>
        /// <param name="targetBar"></param>
        /// <param name="targetValue"></param>
        /// <param name="duration"></param>
        /// <returns></returns>
        private IEnumerator BarChangeAnim(Image targetBar, float targetValue, float duration)
        {
            float elapsed = 0f;
            float cur = 1 - targetBar.fillAmount;

            while (elapsed < duration)
            {
                elapsed += Time.deltaTime; // 累计时间
                float currentValue = Mathf.Lerp(cur, targetValue, elapsed / duration);

                // 更新 UI
                targetBar.fillAmount = 1 - currentValue;

                yield return null;
            }

            //// 确保最终值精确为 target
            //targetBar.fillAmount = 1 - targetValue;
        }

    }
}